package control;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import book.Book;

import service.Robot;
import util.HttpUtil;
import util.PropertiesUtil;

public class WallControl extends HttpServlet{
	private static String savePath = (String)PropertiesUtil.loadPropertiesFile().get("download_path");
	
	private Map bookMap = new HashMap();
	private Map bookIdMap = new HashMap();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if("downloadAllTxt".equals(action)){
			this.downloadAllTxt(request, response);
			//return;
		}else if("downloadAllChm".equals(action)){
			this.downloadAllChm(request, response);
			//return;
		}else if("download".equals(action)){
			this.download(request, response);
			//return;
		}else if("downloadFromLocal".equals(action)){
			this.downloadFromLocal(request, response);
			return;
		}
		
		List list = (List)bookMap.get("qidian");
		if(list ==null ){
			try {
				list = new Robot().parseBooks();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bookMap.put("qidian", list);
			
			for(int i = 0;i<list.size();i++){
				Book book = (Book)list.get(i);
				bookIdMap.put(book.getBookId(), book);
			}
		}
		
		//根据书名进行搜索
		List searchList = new ArrayList();
		String bookName = request.getParameter("bookName");
		//System.out.println("bookName1 = " + bookName);
		if(bookName!=null && !"".equals(bookName.trim())){
			bookName = new String(bookName.getBytes("ISO-8859-1"),"utf-8");
			//System.out.println("bookName2 = " + bookName);
			bookName = bookName.trim();
			for(int i = 0;i<list.size();i++){
				Book book = (Book)list.get(i);
				String name = book.getName();
				if(name.trim().indexOf(bookName)!=-1){
					searchList.add(book);
				}
			}
			request.setAttribute("bookName", bookName);
			request.setAttribute("bookList", searchList);
		}else{
			request.setAttribute("bookList", list);
		}
		
		request.getRequestDispatcher("/book/listBook.jsp").forward(request, response);
	}
	
	private void downloadAllTxt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List list = (List)bookMap.get("qidian");
		for(int i = 0;i<5;i++){
			Book book = (Book)list.get(i);
			String name = book.getName();
			String txtUrl = book.getTxtUrl();
			HttpUtil.downloadFile(txtUrl, savePath + name + ".txt");
			
		}
	}
	
	private void downloadAllChm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List list = (List)bookMap.get("qidian");
		for(int i = 0;i<5;i++){
			Book book = (Book)list.get(i);
			String name = book.getName();
			String chmUrl = book.getChmUrl();
			HttpUtil.downloadFile(chmUrl, savePath + name + ".chm");
		}
	}
	
	private void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] bookIdArr = request.getParameterValues("fid");
		for(int i = 0;i<bookIdArr.length;i++){
			Book book = (Book)bookIdMap.get(bookIdArr[i]);
			String name = book.getName();
			String chmUrl = book.getChmUrl();
			HttpUtil.downloadFile(chmUrl, savePath + name + ".chm");
		}
	}
	
	private void downloadFromLocal(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String bookId = request.getParameter("bookId");
		Book book = (Book) bookIdMap.get(bookId);
		String fileName = book.getName() + ".chm";

		String fileName2 = URLDecoder.decode(fileName,"UTF-8"); 
		fileName2 = URLEncoder.encode(fileName2,"UTF-8"); 

		// 设置响应头和下载保存的文件名 
		//response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8"); 
		response.setContentType("application/x-download"); 
		response.setHeader("Content-Disposition", "attachment; filename=\"" 
		+ fileName2 + "\""); 
		//response.setCharacterEncoding("UTF-8"); 

		// 打开指定文件的流信息
		FileInputStream fileInputStream = new FileInputStream(savePath
				+ fileName);

		// 写出流信息
		OutputStream out = response.getOutputStream();
		int i;
		while ((i = fileInputStream.read()) != -1) {
			out.write(i);
		}
		fileInputStream.close();
		out.close(); 
	}
}	
